package com.xianyun.site.support.message;

import com.alibaba.fastjson.JSONObject;
import com.xianyun.common.redis.service.RedisService;
import com.xianyun.site.support.api.ReceiveService;
import com.xianyun.site.support.common.exception.SupportErrorCode;
import com.xianyun.site.support.common.exception.SupportException;
import com.xianyun.site.support.convertor.ReceiveConvertor;
import com.xianyun.site.support.domain.model.ReceiveMessage;
import com.xianyun.site.support.dto.ReceiveCmd;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.concurrent.TimeUnit;

/**
 * 三方数据支撑服务消息接收
 * @author mac_zyj
 */
@Slf4j
@Service
@RocketMQMessageListener(topic = "SUPPORT_MESSAGE",consumerGroup = "SUPPORT_CONSUMER")
public class SupportRocketMqAdapter implements RocketMQListener<JSONObject> {

    /**Redis服务*/
    @Autowired
    private RedisService redisService;

    @Autowired
    private ReceiveService receiveService;

    @Override
    public void onMessage(JSONObject jsonObject) {
        ReceiveCmd receiveCmd = jsonObject.toJavaObject(ReceiveCmd.class);
        isMessageBlock(ReceiveConvertor.toEntity(receiveCmd));
        receiveService.sendSupportMessage(receiveCmd,jsonObject);
    }


    private void isMessageBlock(ReceiveMessage  receiveMessage){
        String checkKey = receiveMessage.getRedisCheckKey("_CHECK");
        log.info("支持服务消息接收------Redis校验Key："+receiveMessage.getRedisCheckKey()+"----操作码:"+receiveMessage.getOperateCode());
        if (null!=redisService.getCacheObject(checkKey)){
            log.info("消息拥塞----初始拦截---"+checkKey+"---弃用--"+receiveMessage.getCurrentTime()+"-事务编号----"+receiveMessage.getTransactionId());
            throw new SupportException(SupportErrorCode.SYS_MQ_BLOCK,"消息拥塞");
        }
        else {
            redisService.setCacheObject(checkKey,receiveMessage.getTransactionId(),50, TimeUnit.SECONDS);
        }
    }
}
